package com.gzhryc.common.sms;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class WebchineseSmsHandler implements ISmsHandler{
	
	private String key = "humphrey";
	private String secret = "d24ab755ad46d10c3c01";
	private String smsUrl = "http://%s.sms.webchinese.cn/";
	
	public WebchineseSmsHandler(){}
	
	public WebchineseSmsHandler(String smsUrl,String key,String secret){
		this.smsUrl = smsUrl;
		this.key = key;
		this.secret = secret;
	}
	
	public WebchineseSmsHandler(String key,String secret){
		this.key = key;
		this.secret = secret;
	}

	public boolean send(SmsMessage msg) {
		CloseableHttpResponse response = null;
		try{
			CloseableHttpClient httpclient = HttpClients.createDefault();
			String url = String.format(smsUrl, msg.getCharset().name().replace("-", ""));
		
			Header[] headers = new Header[] { new BasicHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=" + msg.getCharset()) };
			
			if(SmsPhoneVerifyMessage.class.isInstance(msg)) {
				msg.setContent("尊敬的用户，您本次的验证码："+msg.getContent()+"，10分钟内输入有效，感谢使用本平台");
			}
			
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("Uid", key));
			formparams.add(new BasicNameValuePair("Key", secret));
			formparams.add(new BasicNameValuePair("smsMob", msg.getPhone()));
			formparams.add(new BasicNameValuePair("smsText", filtrate(msg.getContent())));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,msg.getCharset());
			HttpPost httppost = new HttpPost(url);
			httppost.setHeaders(headers);
			httppost.setEntity(entity);

			response = httpclient.execute(httppost);
			HttpEntity respEntity = response.getEntity();
			if(entity != null){
				String result = EntityUtils.toString(respEntity,msg.getCharset());
				if(StringUtils.isNotBlank(result)){
					if(Integer.parseInt(result) > 0){
						return true;
					}else{
						System.out.println(result);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
	
	private static String filtrate(String msg){
		msg = msg.replace("代金券", "代 金 券");
		return msg;
	}

	@Override
	public String getType() {
		return "Webchinese";
	}

}
